﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;

namespace CommTest.Generic
{
    internal class BuildClass
    {
        public static void Test()
        {
            var classText = @"
using System;
using System.Text;

namespace CommonTest
{
    public class User2
    {
        public string _key;
        public long Id { get; set; }
        public string Name { get; }
        public string Address { get; private set; }

        static void Main(string[] args)
        {
            Console.WriteLine(""Hello, World!"");
        }
    }
}
";
            AssemblyBuilder assemblyBuilder;
            ModuleBuilder moduleBuilder;
            TypeBuilder typeBuilder;
            //CSharpCodeProvider;
            SyntaxTree tree = CSharpSyntaxTree.ParseText(classText);
            //var root = tree.GetRoot();
            //var nodes = root.DescendantNodes;
            var root = tree.GetCompilationUnitRoot();
            var nodes = root.DescendantNodes();
            var compilation = CSharpCompilation.Create("User2")
                //.AddReferences(MetadataReference.CreateFromFile(
                //    typeof(string).Assembly.Location))
                .AddSyntaxTrees(tree);

            SemanticModel model = compilation.GetSemanticModel(tree);

            UsingDirectiveSyntax usingSystem = root.Usings[0];
            NameSyntax systemName = usingSystem.Name;
            SymbolInfo symbols = model.GetSymbolInfo(systemName);

            LiteralExpressionSyntax stringExpressionSyntax = nodes.OfType<LiteralExpressionSyntax>().FirstOrDefault();
            TypeInfo stringTypeInfo = model.GetTypeInfo(stringExpressionSyntax);
            var stringTypesSymbols = (INamedTypeSymbol)stringTypeInfo.Type;
            var stringMembers = stringTypesSymbols.GetMembers();

            ClassDeclarationSyntax userClassSyntax = nodes.OfType<ClassDeclarationSyntax>().FirstOrDefault();
            var lastNode = userClassSyntax.Members.OfType<PropertyDeclarationSyntax>().Last();
            var isPublic = lastNode.Modifiers.Any(s=> s.Kind() == SyntaxKind.PublicKeyword);
            var acces = lastNode.AccessorList.Accessors.FirstOrDefault();
            var accessKey = acces.Keyword;

            var members = model.GetMemberGroup(tree.GetRoot());

            var assembly = typeof(BuildClass).Assembly;
            var module = assembly.GetModules().First();

        }
    }
}


namespace CommonTest
{
    using System;
    using System.Text;

    public class User2
    {
        public long Id { get; set; }
    }
}
